<template>
  <div id="flowReport">
    <!-- 小循环报表 2018/8/23 zhangQ -->
    <Form :model="searchForm" inline>
      <FormItem label="到站时间段">
        <DatePicker type="daterange" v-model="searchForm.timeSlot" style="width: 200px" :clearable="false"></DatePicker>
      </FormItem>
      <FormItem label="站名">
        <!--<i-input type="text" placeholder="场站"></i-input>-->
        <!--<Select v-model="searchForm.stationName" style="width: 200px;" :clearable="true">-->
        <!--<template v-for="item in stationNameList">-->
        <!--<Option :value="item.endStationName">{{ item.endStationName }}</Option>-->
        <!--</template>-->
        <!--</Select>-->
        <selectAuto
          v-model="searchForm.stationName" field="stationName" label="stationName" search-keys="stationName,py" :dataList="stationCodesDict" :dropAll="true" :width="150"></selectAuto>
      </FormItem>

      <!--<FormItem label="箱型">-->
      <!--<i-input type="text" v-model="searchForm.sender"></i-input>-->
      <!--</FormItem>-->
      <FormItem label="箱型">
        <!--<Select v-model="searchForm.containerType" clearable placeholder="请选择箱型" style="width: 200px">-->
        <!--<template v-for="item in containerTypeList">-->
        <!--<Option :value="item">{{ item }}</Option>-->
        <!--</template>-->
        <!--</Select>-->
        <selectAuto
          v-model="searchForm.containerType" field="containerType" label="containerType" search-keys="containerType,py" :dataList="containerTypesDict" :dropAll="true" :width="200"></selectAuto>
      </FormItem>

      <FormItem label="发货人">
        <!--<i-input type="text" v-model="searchForm.sender"></i-input>-->
        <selectAuto
          v-model="searchForm.sender" field="sender" label="sender" search-keys="senderPingYin,sender" :dataList="senderDict" :dropAll="true" :width="200"></selectAuto>
      </FormItem>

      <FormItem label="收货人">
        <!--<i-input type="text" v-model="searchForm.receiver"></i-input>-->
        <selectAuto
          v-model="searchForm.receiver" field="receiver" label="receiver" search-keys="receiverPingYin,receiver" :dataList="receiverDict" :dropAll="true" :width="200"></selectAuto>
      </FormItem>

      <!--<FormItem label="箱号">-->
      <!--<i-input type="text" v-model="searchForm.containerNo"></i-input>-->
      <!--</FormItem>-->

      <FormItem label="箱属">
        <!--<i-input type="text" v-model="searchForm.containerOwner"></i-input>-->
        <selectAuto
          v-model="searchForm.containerOwner" field="containerOwner" label="containerOwner" search-keys="containerOwner,py" :dataList="containerUsersDict" :dropAll="true" :width="200"></selectAuto>
      </FormItem>
      <!--<FormItem label="车队">-->
      <!--<i-input type="text" v-model="searchForm.fleetName" disabled></i-input>-->
      <!--</FormItem>-->
      <FormItem>
        <Button type="primary" @click="getMinorCycleDataAction">搜索</Button>
        <Button type="primary" @click="exportExcel">
          导出excel
        </Button>
      </FormItem>
    </Form>

    <staticTable ref="flowTabRef">
      <i-table :columns="flowObj.flowColumn" :data="flowObj.flowData" :height="flowObj.tableHeight"></i-table>
      <div style="margin-top: 15px">
        <div style="display: inline-block;margin-right: 15px;"><span>总计{{  }}</span></div>
        <div style="display: inline-block;margin-right: 15px;"><span>到达箱数：{{ allData.allTotalCount }}</span></div>
        <div style="display: inline-block;margin-right: 15px;"><span>已发出数：{{allData.yTotalCount}}</span></div>
        <div style="display: inline-block;margin-right: 15px;"><span>已发出停留时长：{{allData.yStayTime.toFixed(2)}}</span></div>
        <div style="display: inline-block;margin-right: 15px;"><span>未发出数：{{allData.wTotalCount}}</span></div>
        <div style="display: inline-block;margin-right: 15px;"><span>未发出停留时长：{{allData.wStayTime.toFixed(2)}}</span></div>
        <div style="display: inline-block;margin-right: 15px;"><span>平均停留时长：{{allData.avgTime.toFixed(2)}}</span></div>
      </div>
    </staticTable>

    <xlinkModal v-model="operaModal.flowModalShow" :title="flowObj.currentObj.endStationName+' 查看详情' " className="vertical-center-modal" width="980px;">
      <flowReportDetail :searchObj="searchForm" :currentObj="flowObj.currentObj" @close="detailClose"></flowReportDetail>
    </xlinkModal>
  </div>
</template>

<script>
  // import hw from '@/components/common/heightAndWidth'
  import moment from 'moment'
  import staticTable from '@/components/staticTable'
  import xlinkModal from '@/components/modal/xlinkModal'
  import { exportUtil } from '@/vendor/exportInvoke'
  // import { getMinorCycleData } from '@/api/containerPlatform/report'
  // import { getContainersPositionList, getContainersTypeList } from '@/api/containerPlatform/containerManagement'
  import { getMinorCycleData } from '@/api/containerPlatform/logistics'
  import flowReportDetail from './flowReportDetail'
  import containerDictMixins from '../containerDictMixins'
  import selectAuto from '@/components/selectAuto'
  import _ from 'lodash'

  export default {
    name: 'flowReport',
    mixins: [containerDictMixins],
    data () {
      let searchForm = {
        timeSlot: [moment().subtract(1, 'days').format('YYYY-MM-DD'), moment().format('YYYY-MM-DD')],
        timeStart: moment().subtract(1, 'days').format('YYYY-MM-DD'),
        timeEnd: moment().format('YYYY-MM-DD'),
        stationName: '',
        sender: '',
        receiver: '',
        containerNo: '',
        containerOwner: '',
        fleetName: '',
        containerType: ''
      }
      let stationNameList = []
      let containerTypeList = []
      let flowObj = {
        flowColumn: [
          {
            type: 'index',
            width: 60
          },
          {
            title: '站名',
            width: 300,
            key: 'endStationName'
          },
          {
            title: '到达箱数',
            width: 200,
            key: 'allTotalCount'
          },
          {
            title: '已发出数',
            width: 200,
            key: 'yTotalCount'
          },
          {
            title: '已发出停留时长',
            width: 200,
            key: 'yStayTime'
          },
          {
            title: '未发出数',
            width: 200,
            key: 'wTotalCount'
          },
          {
            title: '未发出停留时长',
            width: 200,
            key: 'wStayTime'
          },
          {
            title: '平均停留时长',
            width: 200,
            key: 'avgTime'
          }
          // {
          //   title: '在站均时',
          //   width: 300,
          //   key: 'minorcycle',
          //   render: (h, params) => {
          //     return (<span>{params.row.minorcycle.toFixed(2) + ' h'}</span>)
          //   }
          // },
          // {
          //   title: '操作',
          //   minWidth: 300,
          //   render: (h, params) => {
          //     let btnArray = []
          //     btnArray.push(<i-button type="primary" size="small" style="margin-right: 5px;" onClick={() => this.flowViewDetail(params.row)}>查看详情</i-button>)
          //     // params.row.menuType === 1 && (btnArray.push(<i-button type="primary" size="small" style="margin-right: 5px;" onClick={() => this.powerMenuAdd(params.index, params.row)}>添加子项</i-button>))
          //     return (btnArray)
          //   }
          // }
        ],
        flowData: [],
        tableHeight: 500,
        currentObj: {}
      }
      let allData = { endStationName: '总计', wStayTime: 0, wTotalCount: 0, yStayTime: 0, yTotalCount: 0, avgTime: 0, allTotalCount: 0 }
      let operaModal = { flowModalShow: false }
      let datas = { flowObj, searchForm, stationNameList, operaModal, containerTypeList, allData }
      return datas
    },
    computed: {},
    watch: {
      'operaModal.flowModalShow' (val) {
        !val && (this.flowObj.currentObj = {})
      },
      'searchForm.timeSlot' (val, oldVal) {
        if (val && val.length > 0 && val[0] && val[1]) {
          this.searchForm.timeStart = moment(val[0]).format('YYYY-MM-DD') + ' 00:00:00'
          this.searchForm.timeEnd = moment(val[1]).format('YYYY-MM-DD') + ' 23:59:59'
        } else {
          if (oldVal && oldVal.length > 0 && oldVal[0] && oldVal[1]) {
            this.$nextTick(() => {
              this.searchForm.timeSlot = oldVal
            })
          }
        }
        // console.log(this.searchForm)
      }
    },
    methods: {
      exportExcel () {
        let result = this.fasetJson(this.flowObj.flowData)
        exportUtil.export2Excel('效率分析' + Date.now(), result.columns, result.data)
      },
      fasetJson (data) {
        let index = 0
        data.forEach((item) => {
          item.index = index++
        })
        let result = {
          columns: [{ title: '序号', key: 'index' },
            { title: '站名', key: 'endStationName' },
            { title: '到达箱数', key: 'allTotalCount' },
            { title: '已发出数', key: 'yTotalCount' },
            { title: '已发出停留时长', key: 'yStayTime' },
            { title: '未发出数', key: 'wTotalCount' },
            { title: '未发出停留时长', key: 'wStayTime' },
            { title: '平均停留时长', key: 'avgTime' }
          ],
          data: data
        }
        return result
      },
      /**
       * TODO(查看详情)
       * @auther zhangQ
       * @date 2018/8/23 15:12
       */
      flowViewDetail (row) {
        console.log('flowViewDetailflowViewDetail')
        this.flowObj.currentObj = row
        this.operaModal.flowModalShow = true
      },
      /**
       * TODO(获取小循环报表内容)
       * @auther zhangQ
       * @date 2018/8/23 18:58
       */
      getMinorCycleDataAction () {
        getMinorCycleData(this.searchForm)
          .then(res => {
            if (+res.data.isSuccess === 1) {
              this.$Notice.success({
                title: '获取成功！'
              })
              let groupFlow = _.groupBy(res.data.data, 'endStationName')
              let resData = []
              let allData = { endStationName: '总计', wStayTime: 0, wTotalCount: 0, yStayTime: 0, yTotalCount: 0, avgTime: 0, allTotalCount: 0 }
              _.forIn(groupFlow, (value, key) => {
                let itemObj = { endStationName: key, wStayTime: 0, wTotalCount: 0, yStayTime: 0, yTotalCount: 0, avgTime: 0, allTotalCount: 0 }
                value.forEach((item) => {
                  if (item.curState === '未发出') {
                    itemObj.wStayTime = item.stayTime.toFixed(2)
                    itemObj.wTotalCount = item.totalcount
                  } else if (item.curState === '已发出') {
                    itemObj.yStayTime = item.minorcycle.toFixed(2)
                    itemObj.yTotalCount = item.totalcount
                  }
                })
                itemObj.allTotalCount = (+itemObj.wTotalCount) + (+itemObj.yTotalCount)
                itemObj.avgTime = (((itemObj.wStayTime * itemObj.wTotalCount) + (itemObj.yStayTime * itemObj.yTotalCount)) / itemObj.allTotalCount).toFixed(2)
                allData.wStayTime += +itemObj.wStayTime
                allData.wTotalCount += +itemObj.wTotalCount
                allData.yStayTime += +itemObj.yStayTime
                allData.yTotalCount += +itemObj.yTotalCount
                allData.avgTime += +itemObj.avgTime
                allData.allTotalCount += +itemObj.allTotalCount
                resData.push(itemObj)
              })
              this.allData = allData
              this.flowObj.flowData = resData
              // this.stationNameList = res.data.data
            }
          })
      },
      /**
       * TODO(detail 详情关闭)
       * @auther zhangQ
       * @date 2018/8/23 19:26
       */
      detailClose () {
        this.operaModal.flowModalShow = false
      }
    },
    created () {
    },
    mounted () {
      this.getSenderListDB()
      this.getReceiverListDB()
      this.getContainersPositionListDB()
      // this.getStateListDB()
      this.getContainersTypeListDB()
      this.getContainerOwnerListDB()
      // getContainersTypeList().then(res => {
      //   if (res.data.isSuccess === 1) {
      //     this.containerTypeList = res.data.data
      //   }
      // })
      // getContainersPositionList({ isAll: 0 })
      //   .then(res => {
      //     if (+res.data.isSuccess === 1) {
      //       let stationObjs = []
      //       res.data.data.forEach(r => {
      //         stationObjs.push({ 'endStationName': r })
      //       })
      //       this.stationNameList = stationObjs
      //     }
      //   })
      // hw.setFullHeightAllWith('flowReport', 90, (height) => {
      //   this.flowObj.tableHeight = height
      // })
      this.getMinorCycleDataAction()
    },
    components: { staticTable, xlinkModal, flowReportDetail, selectAuto }
  }
</script>

<style scoped>

</style>
